import { defineStore } from 'pinia';
import { showToast } from '@/utils/toast';

// 权限管理状态仓库
export const usePermissionStore = defineStore('permission', {
  state: () => ({
    // 权限组列表
    permissionGroups: [],
    // 所有权限列表
    allPermissions: [],
    // 加载状态
    loading: {
      groups: false,
      permissions: false,
      submit: false
    },
    // 缓存的权限数据
    cachedPermissions: {
      byUser: {},
      byRole: {}
    }
  }),

  getters: {
    // 获取权限组数量
    permissionGroupCount: (state) => state.permissionGroups.length,
    
    // 根据ID获取权限组
    getPermissionGroupById: (state) => (id) => {
      return state.permissionGroups.find(group => group.id === id) || null;
    },
    
    // 获取权限组及其包含的权限
    getGroupsWithPermissions: (state) => {
      return state.permissionGroups.map(group => ({
        ...group,
        permissions: state.allPermissions.filter(permission => permission.groupId === group.id)
      }));
    }
  },

  actions: {
    /**
     * 获取所有权限组（不带权限列表）
     */
    async getPermissionGroups() {
      try {
        this.loading.groups = true;
        const response = await requestInstance.get('permission-groups');
        this.permissionGroups = response.data || [];
        return this.permissionGroups;
      } catch (error) {
        console.error('获取权限组失败:', error);
        showToast('获取权限组失败', 'error');
        return [];
      } finally {
        this.loading.groups = false;
      }
    },
    
    /**
     * 获取所有权限组及其包含的权限
     */
    async getPermissionGroupsWithPermissions() {
      try {
        this.loading.groups = true;
        const response = await requestInstance.get('permission-groups/with-permissions');
        this.permissionGroups = response.data || [];
        
        // 提取所有权限并去重
        const permissions = [];
        this.permissionGroups.forEach(group => {
          if (group.permissions && Array.isArray(group.permissions)) {
            group.permissions.forEach(permission => {
              if (!permissions.some(p => p.id === permission.id)) {
                permissions.push(permission);
              }
            });
          }
        });
        this.allPermissions = permissions;
        
        return this.permissionGroups;
      } catch (error) {
        console.error('获取权限组及权限失败:', error);
        showToast('获取权限组及权限失败', 'error');
        return [];
      } finally {
        this.loading.groups = false;
      }
    },
    
    /**
     * 获取所有权限
     */
    async getAllPermissions() {
      try {
        this.loading.permissions = true;
        const response = await requestInstance.get('permissions');
        this.allPermissions = response.data || [];
        return this.allPermissions;
      } catch (error) {
        console.error('获取所有权限失败:', error);
        showToast('获取权限列表失败', 'error');
        return [];
      } finally {
        this.loading.permissions = false;
      }
    },
    
    /**
     * 获取用户拥有的权限
     * @param {string|number} userId - 用户ID
     */
    async getUserPermissions(userId) {
      try {
        // 先检查缓存
        if (this.cachedPermissions.byUser[userId]) {
          return this.cachedPermissions.byUser[userId];
        }
        
        const response = await requestInstance.get(`/api/users/${userId}/permissions`);
        const permissions = response.data || [];
        
        // 缓存结果
        this.cachedPermissions.byUser[userId] = permissions;
        return permissions;
      } catch (error) {
        console.error(`获取用户${userId}的权限失败:`, error);
        showToast('获取用户权限失败', 'error');
        return [];
      }
    },
    
    /**
     * 获取角色拥有的权限
     * @param {string|number} roleId - 角色ID
     */
    async getRolePermissions(roleId) {
      try {
        // 先检查缓存
        if (this.cachedPermissions.byRole[roleId]) {
          return this.cachedPermissions.byRole[roleId];
        }
        
        const response = await requestInstance.get(`/api/roles/${roleId}/permissions`);
        const permissions = response.data || [];
        
        // 缓存结果
        this.cachedPermissions.byRole[roleId] = permissions;
        return permissions;
      } catch (error) {
        console.error(`获取角色${roleId}的权限失败:`, error);
        showToast('获取角色权限失败', 'error');
        return [];
      }
    },
    
    /**
     * 创建权限组
     * @param {Object} group - 权限组数据
     */
    async createPermissionGroup(group) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.post('permission-groups', group);
        const newGroup = response.data;
        
        // 更新本地状态
        this.permissionGroups.push(newGroup);
        showToast('权限组创建成功', 'success');
        return newGroup;
      } catch (error) {
        console.error('创建权限组失败:', error);
        showToast(error.response?.data?.message || '创建权限组失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新权限组
     * @param {string|number} id - 权限组ID
     * @param {Object} group - 权限组数据
     */
    async updatePermissionGroup(id, group) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.put(`/api/permission-groups/${id}`, group);
        const updatedGroup = response.data;
        
        // 更新本地状态
        const index = this.permissionGroups.findIndex(g => g.id === id);
        if (index !== -1) {
          this.permissionGroups[index] = { ...this.permissionGroups[index], ...updatedGroup };
        }
        
        showToast('权限组更新成功', 'success');
        return updatedGroup;
      } catch (error) {
        console.error(`更新权限组${id}失败:`, error);
        showToast(error.response?.data?.message || '更新权限组失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 删除权限组
     * @param {string|number} id - 权限组ID
     */
    async deletePermissionGroup(id) {
      try {
        this.loading.submit = true;
        await requestInstance.delete(`/api/permission-groups/${id}`);
        
        // 更新本地状态
        this.permissionGroups = this.permissionGroups.filter(group => group.id !== id);
        // 同时删除该组下的所有权限
        this.allPermissions = this.allPermissions.filter(permission => permission.groupId !== id);
        
        showToast('权限组删除成功', 'success');
        return true;
      } catch (error) {
        console.error(`删除权限组${id}失败:`, error);
        showToast(error.response?.data?.message || '删除权限组失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 创建权限
     * @param {Object} permission - 权限数据
     */
    async createPermission(permission) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.post('permissions', permission);
        const newPermission = response.data;
        
        // 更新本地状态
        this.allPermissions.push(newPermission);
        
        showToast('权限创建成功', 'success');
        return newPermission;
      } catch (error) {
        console.error('创建权限失败:', error);
        showToast(error.response?.data?.message || '创建权限失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新权限
     * @param {string|number} id - 权限ID
     * @param {Object} permission - 权限数据
     */
    async updatePermission(id, permission) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.put(`/api/permissions/${id}`, permission);
        const updatedPermission = response.data;
        
        // 更新本地状态
        const index = this.allPermissions.findIndex(p => p.id === id);
        if (index !== -1) {
          this.allPermissions[index] = { ...this.allPermissions[index], ...updatedPermission };
        }
        
        // 如果权限组ID变更，需要更新权限组缓存
        if (permission.groupId && this.allPermissions[index].groupId !== permission.groupId) {
          this.getPermissionGroupsWithPermissions();
        }
        
        showToast('权限更新成功', 'success');
        return updatedPermission;
      } catch (error) {
        console.error(`更新权限${id}失败:`, error);
        showToast(error.response?.data?.message || '更新权限失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 删除权限
     * @param {string|number} id - 权限ID
     */
    async deletePermission(id) {
      try {
        this.loading.submit = true;
        await requestInstance.delete(`/api/permissions/${id}`);
        
        // 更新本地状态
        this.allPermissions = this.allPermissions.filter(permission => permission.id !== id);
        
        // 清除相关缓存
        Object.keys(this.cachedPermissions.byUser).forEach(userId => {
          this.cachedPermissions.byUser[userId] = this.cachedPermissions.byUser[userId]
            .filter(p => p.id !== id);
        });
        
        Object.keys(this.cachedPermissions.byRole).forEach(roleId => {
          this.cachedPermissions.byRole[roleId] = this.cachedPermissions.byRole[roleId]
            .filter(p => p.id !== id);
        });
        
        showToast('权限删除成功', 'success');
        return true;
      } catch (error) {
        console.error(`删除权限${id}失败:`, error);
        showToast(error.response?.data?.message || '删除权限失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新用户权限
     * @param {string|number} userId - 用户ID
     * @param {Array} permissionIds - 权限ID数组
     */
    async updateUserPermissions(userId, permissionIds) {
      try {
        this.loading.submit = true;
        await requestInstance.put(`/api/users/${userId}/permissions`, { permissionIds });
        
        // 更新缓存
        this.cachedPermissions.byUser[userId] = this.allPermissions
          .filter(permission => permissionIds.includes(permission.id));
        
        showToast('用户权限更新成功', 'success');
        return true;
      } catch (error) {
        console.error(`更新用户${userId}的权限失败:`, error);
        showToast(error.response?.data?.message || '更新用户权限失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新角色权限
     * @param {string|number} roleId - 角色ID
     * @param {Array} permissionIds - 权限ID数组
     */
    async updateRolePermissions(roleId, permissionIds) {
      try {
        this.loading.submit = true;
        await requestInstance.put(`/api/roles/${roleId}/permissions`, { permissionIds });
        
        // 更新缓存
        this.cachedPermissions.byRole[roleId] = this.allPermissions
          .filter(permission => permissionIds.includes(permission.id));
        
        showToast('角色权限更新成功', 'success');
        return true;
      } catch (error) {
        console.error(`更新角色${roleId}的权限失败:`, error);
        showToast(error.response?.data?.message || '更新角色权限失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 清除权限缓存
     */
    clearPermissionCache() {
      this.cachedPermissions = {
        byUser: {},
        byRole: {}
      };
    }
  }
});
